import {FC, useEffect} from "react"
import {useRoutes,useLocation,useNavigate} from "react-router-dom"
import useStorage from "./useStorage"

interface Iprops {
    routes:ItemRoute[]
    keyToken:string
}

const useRouteGuard:FC<Iprops> = (props)=>{
    let {routes,keyToken} = props
    
    let [token,] = useStorage(keyToken)
    // let token = localStorage.getItem(keyToken)
    
    let location = useLocation()
    // console.log('路由守卫',location);
    let navigate = useNavigate()
    let element = useRoutes(routes)
    useEffect(()=>{
        if(!token){
            if(location.pathname !== "/login"){
                navigate('/login')
            }
        }
    },[location.pathname])
    
    return element
}

export default useRouteGuard